package com.mit.wx.controller;

import com.mit.wx.service.AccessTokenService;
import com.mit.wx.wx.WxMenuApi;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 2018/11/4 Create by 郭文梁
 * WxController
 * 微信相关操作控制器
 *
 * @author 郭文梁
 * @date 2018/11/4
 */
@RestController
@RequestMapping("/wx")
public class WxController {
    private final AccessTokenService accessTokenService;

    @Autowired
    public WxController(AccessTokenService accessTokenService) {
        this.accessTokenService = accessTokenService;
    }

    @GetMapping("/create-menu")
    public String createMenu() throws IOException {
        String json = readTemplateJSON();
        if (json == null) {
            throw new NullPointerException("Could not read menu json template from classpath:menu.json");
        }
        String accessToken = accessTokenService.getAccessToken().getAccessToken();
        return WxMenuApi.setMenu(accessToken, json);
    }

    @PostMapping("/create-menu")
    public String createMenu(@RequestBody String json) throws IOException {
        String accessToken = accessTokenService.getAccessToken().getAccessToken();
        return WxMenuApi.setMenu(accessToken, json);
    }

    private String readTemplateJSON() throws IOException {
        File file = ResourceUtils.getFile("classpath:menu.json");
        return FileUtils.readFileToString(file, Charset.forName("UTF-8"));
    }
}
